package com.mycase.im.boot.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.mycase.im.boot.entity.database.ImUser;
import com.mycase.im.boot.exception.CustomException;
import com.mycase.im.boot.mapper.UserMapper;
import com.mycase.im.boot.service.UserService;
import com.mycase.im.boot.utils.UUIDUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.ObjectUtils;

import java.util.Date;
import java.util.List;

/**
 * @Author ZhuHJay
 * @Date 2021/8/2 17:08
 */
@Service
@Transactional(rollbackFor = {CustomException.class})
public class UserServiceImpl extends ServiceImpl<UserMapper, ImUser> implements UserService {

    @Autowired
    private BCryptPasswordEncoder passwordEncoder;

    @Override
    public List<ImUser> getUserList(String id) {
        QueryWrapper<ImUser> queryWrapper = new QueryWrapper<>();
        queryWrapper
                // 进行字段查询时排除对应项(判断为false则排除)
                .select(ImUser.class, bean -> !"password".equals(bean.getColumn()));

        List<ImUser> userList = list(queryWrapper);

        // 排除该id的信息
        for (int i = 0; i < userList.size(); i++) {
            ImUser imUser = userList.get(i);
            if( imUser.getId().equals(id) ){
                userList.remove(i);
                break;
            }
        }

        return userList;
    }

    @Override
    public ImUser getUserInfoById(String id) {
        QueryWrapper<ImUser> imUserQueryWrapper = new QueryWrapper<>();
        imUserQueryWrapper
                .eq("id", id)
                .select(ImUser.class, bean -> !"password".equals(bean.getColumn()));
        return getOne(imUserQueryWrapper);
    }

    @Override
    public void register(ImUser imUser) {
        // 判断账号(手机号)是否被使用过
        QueryWrapper<ImUser> imUserQueryWrapper = new QueryWrapper<>();
        imUserQueryWrapper.eq("account", imUser.getAccount());
        ImUser isExist = getOne(imUserQueryWrapper);
        if( !ObjectUtils.isEmpty(isExist) ){
            throw new CustomException("该手机号已经被使用了");
        }

        // 补全 JavaBean 数据信息
        imUser.setCreateTime(new Date());
        // 密码进行加密
        imUser.setPassword(
            passwordEncoder.encode( imUser.getPassword() )
        );
        // 将数据添加到数据库中
        if( baseMapper.insert(imUser) != 1 ){
            throw new CustomException("数据添加失败");
        }
    }

    @Override
    public Boolean isExist(String id) {
        return getOne(new QueryWrapper<ImUser>().eq("id", id)) != null;
    }

}
